package top.bulk.dbcrypto.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import top.bulk.dbcrypto.util.AnnUtil;
import top.bulk.dbcrypto.util.CryptoUtil;

/**
 * 用于加密的拦截器， 拦截所有insert和update操作
 *
 * @author 散装java
 * @date 2024-08-01
 */
@Slf4j
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class BulkEncryptInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        // 获取参数对象
        Object parameterObject = args[1];
        try {
            AnnUtil.doFiled(parameterObject, CryptoUtil::aesEncrypt);
        } catch (Exception e) {
            log.error("BulkEncryptInterceptor error:{}", e.getMessage(), e);
        }
        return invocation.proceed();
    }
}
